/*
 * @Description: 
 * @Author: houcw
 * @Date: 2024-01-25 14:43:03
 * @LastEditTime: 2024-01-26 12:10:07
 * @LastEditors: houcw
 * @Reference: 
 */
var express = require('express');
const bcrypt = require('bcryptjs');
var router = express.Router();
let User = require('../model/User');
let { setToken } = require('../tool/token')

async function hashPassword(password, saltRounds = 10) {
  // 使用bcrypt生成安全的盐值并加密密码
  return await bcrypt.hash(password, saltRounds);
}

// 加密密码
async function handelPassword(password) {
  const hashedPassword = await hashPassword(password)
  return hashedPassword
}

// 解密密码 判断用户登录密码是否正确

async function handelPasswordCompare(inputPassword, dbPassword) {
  console.log(inputPassword,'inputPassword')
  console.log(dbPassword,'dbPassword')
  let isEqual = await bcrypt.compare(inputPassword, dbPassword);
  console.log(isEqual)
  return isEqual
}

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

// 用户注册
router.post('/register', function (req, res, next) {
  const account = req.body.account
  const password = req.body.password;

  User.findOne({ account: account }, (err, data) => {
    if (err) {
      res.json({
        status: 400,
        msg: "数据读取失败！"
      });
    } else if (data) {
      console.log(data, '查询结果')
      res.json({
        status: 200,
        msg: "该用户名已被注册，请选用其他用户名"
      });
    } else {
      //密码加密
      handelPassword(password).then(result => {
        req.body.password = result
        User.create({ ...req.body }, (err1, data1) => {
          if (err1) {
            res.json({
              status: 400,
              msg: err.message
            });
          } else {
            res.json({
              status: 200,
              msg: '新增成功'
            })
          }
        })
      })
    }
  })
})


// 用户登录

router.post('/login', function (req, res, next) {
  let { account, password } = req.body
  User.findOne({ account: account }, (err, data) => {
    if (err) {
      res.json({
        status: 400,
        msg: '该用户还未注册，请先注册'
      })
    } else if (data) {
      console.log(account,'usss')
      if (account != data.account) {
        res.json({
          status: '400',
          msg: '用户名输入不正确'
        })
      }
      handelPasswordCompare(password, data.password).then( res1=> {
        if (res1) {
          let token = setToken(account);
          let data = {
            status: '200',
            msg: '登录成功',
            token
          }
          res.json({
            ...data
          })
        } else {
          res.json({
            status: '400',
            msg: '密码不正确'
          })
        }
      })
    } else {

    }
  })
})

module.exports = router;
